package cn.com.server.common.util.fileexplorer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @author orange
 *
 */
public class FileExplorerUtils {
	
	/**
	 * 递归的方法调用
	 * @param path
	 * @return
	 */
	public static MyFolder traverseFolder(String path) {
		File file = new File(path);
        if (file.exists()) {
        	MyFolder mfo = new MyFolder();
        	mfo.setName(file.getName());
        	mfo.setPath(file.getPath());
        	mfo.setParentPath(file.getParent());
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件夹是空的!");
                return mfo;
            } else {
            	List<MyFolder> mfos = new ArrayList<>();
            	List<MyFile> mfis = new ArrayList<>();
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        mfos.add(traverseFolder(file2.getAbsolutePath()));
                    } else {
                        System.out.println("文件:" + file2.getAbsolutePath());
                        MyFile mfi = new MyFile();
                        mfi.setName(file2.getName());
                        mfi.setPath(file2.getPath());
                        mfi.setSize(file2.length());
                        mfis.add(mfi);
                    }
                }
                mfo.setFolders(mfos);
                mfo.setFiles(mfis);
            }
            return mfo;
        } else {
            System.out.println("文件不存在!");
            return null;
        }
	}
	
	public static void main(String[] args) {
		System.out.println(JSON.toJSONString(traverseFolder("E:\\移动硬盘\\vuedemo")));
	}
}
